<template>
  <view class="second__cat-page">
    <view class="header__box">
      <view class="search__box">
        <search-plugin :chanel="chanel" style="flex: 1;" :queryName="queryName"></search-plugin>
        <view class="icon__box" @tap="changeStatus">
          <image class="icon__image"
            src="https://oss-tencent.bgniao.cn//gruul/20200626/26bffe66093f4086b501a2fce01e9388.png" alt></image>
          <view class="change__item">{{ secondCatGoodsStyle === 1 ? '矩形' : '列表' }}</view>
        </view>
      </view>
    </view>
    <view class="tab__con">
      <view v-for="(i, d) in tabList" :key="d" :class="'tab__item ' + ( activeTab === (d + 1) ? 'active__tab' : '' )"
        @tap="changeActiveTab" :data-index="d + 1">
        <view>{{ i }}</view>
        <view class="price__icon" v-if="d === 3">
          <u-icon size="12" :class="'price__icon_up '" :color="isPrice === 'asc' ? '#FC425A' : '#000' " name="arrow-up"></u-icon>
          <u-icon size="12" :class="'price__icon_down '" :color="isPrice === 'desc' ? '#FC425A' : '#000' " name="arrow-down"></u-icon>
        </view>
      </view>
    </view>
    <view class="list__page" v-if="goodsList.length">
      <second-goodslist @loadMored="loadMored" v-if="secondCatGoodsStyle === 1" :goodsList="goodsList"
        :cartButton="cartButton"></second-goodslist>
      <second-goodsdetail @loadMored="loadMored" v-if="secondCatGoodsStyle === 2" :goodsList="goodsList"
        :cartButton="cartButton"></second-goodsdetail>
    </view>
    <view v-if="!goodsList.length" class="shopNoCar">
      <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/noCar.png" class="shop__noCar"></image>
      <view class="shop__noCar--text">暂无商品~</view>
    </view>
  </view>
</template>

<script lang='ts'>
  import {
    Component,
    Vue
  } from 'vue-property-decorator'
  import {
    getGoodsList,
    searchGoodsList,
    getCouponGoodsList,
  } from "@/api/modules/goods";
  import SecondGoodslist from '../components/second-goodslist/second-goodslist.vue';
  import SecondGoodsdetail from '../components/second-goodsdetail/second-goodsdetail.vue';
  import SearchPlugin from '../components/search-plugin/search-plugin.vue';

  @Component({
    components: {
      SecondGoodslist,
      SecondGoodsdetail,
      SearchPlugin,
    }
  })
  export default class SecondCatgoods extends Vue {

    /** 当前激活tab */
    activeTab: number = 1
    /** tab列表 */
    tabList: string[] = ["综合", "销量", "新品", "价格"]
    /** 列表状态 */
    secondCatGoodsStyle: number = 1 // 1矩形  2列表
    showCategoryId: string = ""
    cartButton: number = 3
    searchForm: any = {
      // 获取商品时搜索对象
      current: 1,
      size: 10,
    }
    hasMore: boolean = true // 是否还有更多
    goodsList: any[] = []
    chanel: number = 0 //  2商超分类页  4首页搜索组件  12商超分类页二级分类导航
    queryName: string = "" // 搜索关键词
    isPrice: string = "" // asc升序 desc降序
    couponId: string = ""

    get saleMode() {
      return this.$store.state.settingStore.saleMode
    }
    // 页面周期函数--监听页面加载
    onLoad(option) {
      if (option.couponId) {
        this.setData({
          couponId: option.couponId,
        });
      }
      this.setData({
          chanel: Number(option.chanel),
          showCategoryId: option.categoryId || "",
          cartButton: option.cartButton || "",
          queryName: option.queryName || "",
        },
        () => {
          this.initData();
        },
      );
    }

    /**
     * 初始化数据
     */
    initData() {
       if (this.chanel === 2 || this.chanel === 12) {
        // 2商超分类页 12商超分类页二级分类导航
          this.getGooodsList();
      } else if (this.chanel === 4) {
        // 4首页搜索组件
        this.searchGoodsList();
      }
    }

    /**
     * 修改列表状态
     */
    changeStatus() {
      this.setData({
        secondCatGoodsStyle: this.secondCatGoodsStyle === 1 ? 2 : 1,
      });
    }

    /**
     * 修改激活tab
     */
    changeActiveTab(e) {
      let isPrice = this.isPrice;
      const activeTab = e.currentTarget.dataset.index;
      if (activeTab === 4) isPrice = this.isPrice === "asc" ? "desc" : "asc";
      else isPrice = "";
      if (activeTab === 3) isPrice = "desc";
      this.setData({
          goodsList: [],
          hasMore: true,
          searchForm: {
            // 获取商品时搜索对象
            current: 1,
            size: 10,
          },
          activeTab,
          isPrice,
        },
        () => {
          this.initData();
        },
      );
    }

    /**
     * 加载更多
     */
    loadMored() {
      this.initData();
    }

    /**
     * 获取商超商品
     */
    getGooodsList() {
      if (!this.hasMore) return;
      const searchForm = {
        ...this.searchForm,
        type: this.activeTab,
        name: this.queryName,
        showCategoryId: this.showCategoryId,
        sort: this.isPrice,
      };
      getGoodsList(searchForm,{}).then(res => {
        const goodsList: any = [];
        res.list.forEach(item => {
          goodsList.push({
            id: Number(item.id),
            name: item.name,
            img: this.returnGoodsImg(item),
            actPrice: item.minPrice,
            price: item.maxPrice,
            soldCount: item.sale,
            inventory: item.inventory,
            deliveryTime: item.goodTime,
            hasTimeTips: item.goodTime && item.goodTime.includes(":"),
          });
        });
        this.setData({
            goodsList: this.goodsList.concat(goodsList),
          },
          () => {
            this.dealSearchParam(res);
          },
        );
      });
    }

    /**
     * 获取商品专区商品
     */
    searchGoodsList() {
      if (!this.hasMore) return;
      const searchForm = {
        ...this.searchForm,
        type: this.activeTab,
        name: this.queryName,
        sort: this.isPrice,
      };
      searchGoodsList(searchForm).then(res => {
        const goodsList: any = [];
        res.list.forEach(item => {
          goodsList.push({
            id: Number(item.id),
            name: item.name,
            img: this.returnGoodsImg(item),
            actPrice: item.minPrice,
            price: item.maxPrice,
            soldCount: item.sale,
            inventory: item.inventory,
            deliveryTime: item.goodTime,
            hasTimeTips: item.goodTime && item.goodTime.includes(":"),
          });
        });
        this.setData({
            goodsList: this.goodsList.concat(goodsList),
          },
          () => {
            this.dealSearchParam(res);
          },
        );
      });
    }

    /**
     * 获取优惠券可用商品
     */
    searchCouponGoodsList() {
      if (!this.hasMore) return;
      const searchForm = {
        ...this.searchForm,
        type: this.activeTab,
        keyword: this.queryName,
        sort: this.isPrice ? this.isPrice : "asc",
      };
      getCouponGoodsList(this.couponId, searchForm).then(res => {
        const goodsList: any = [];
        res.list.forEach(item => {
          goodsList.push({
            id: Number(item.id),
            name: item.name,
            img: this.returnGoodsImg(item),
            actPrice: item.minPrice,
            price: item.maxPrice,
            soldCount: item.sale,
            inventory: item.inventory,
            deliveryTime: item.goodTime,
            hasTimeTips: item.goodTime && item.goodTime.includes(":"),
          });
        });
        this.setData({
            goodsList: this.goodsList.concat(goodsList),
          },
          () => {
            this.dealSearchParam(res);
          },
        );
      });
    }

    /**
     * 处理商品价格
     */
    dealGoodsPrice(item) {
      if (item.minPrice === item.maxPrice) {
        item.maxPrice = "";
      } else if (!item.minPrice && item.maxPrice) {
        item.minPrice = item.maxPrice;
        item.maxPrice = "";
      }
      this.checkGoodsPrice(item);
    }

    /**
     * 检查商品价格是否是数字
     */
    checkGoodsPrice(item) {
      if (item.minPrice) {
        item.minPrice = !isNaN(Number(item.minPrice)) ?
          Number(item.minPrice).toFixed(2) :
          item.minPrice;
      }
      if (item.maxPrice) {
        item.maxPrice = !isNaN(Number(item.maxPrice)) ?
          Number(item.maxPrice).toFixed(2) :
          item.maxPrice;
      }
    }

    /**
     * 处理请求参数
     */
    dealSearchParam(res) {
      const hasMore = this.goodsList.length < res.total;
      const searchForm = this.searchForm;
      if (hasMore) {
        searchForm.current += 1;
      }
      this.setData({
        hasMore,
        searchForm,
      });
    }

    /**
     * 处理商品价格 已购和剩余量
     */
    dealPrice(item) {
      if (item.skuStocks.list === 1) {
        item.price = item.price.toFixed(2);
        item.actPrice = item.originalPrice.toFixed(2);
      } else {
        const priceList = item.skuStocks.map(item => item.originalPrice);
        item.price = Math.min(...priceList).toFixed(2);
        const actPriceList = item.skuStocks.map(item => item.price);
        item.actPrice = Math.min(...actPriceList).toFixed(2);
        item.leadPrice = Math.max(...actPriceList).toFixed(2);
      }
      item.soldCount = item.sale;
      item.skuStocks.forEach(i => {
        i.price = i.price.toFixed(2);
        item.soldCount = item.soldCount + i.sale;
        item.inventory = item.inventory + i.stock;
      });
    }

    /**
     * 处理购买商品的用户头像
     */
    dealUserAttr(item) {
      let userAttrs: any = [];
      if (item.buyerVo && item.buyerVo.buyerList) {
        userAttrs = item.buyerVo.buyerList.map(i => {
          return i.avatar_url;
        });
      }
      return userAttrs.splice(0, 3);
    }

    /**
     * 处理倒计时时间
     */
    dealEndTime(time) {
      time = this.formatTime(time);
      const d1 = new Date(time).getTime();
      const d2 = Date.now();
      const t = d1 - d2;
      let h: any = parseInt(`${t / 3600000}`, 10);
      let s: any = parseInt(`${(t % 3600000) / 60000}`, 10);
      let m: any = parseInt(`${((t % 3600000) % 60000) / 1000}`, 10);
      h = h > 9 ? h : "0" + h;
      s = s > 9 ? s : "0" + s;
      m = m > 9 ? m : "0" + m;
      return {
        time: d1,
        list: [`${h}`, `${s}`, `${m}`],
      };
    }

    /**
     * 处理商品图片
     */
    returnGoodsImg(item) {
      const {
        widePic,
        pic
      } = item;
      let url = pic;
      if (this.secondCatGoodsStyle === 2) {
        url = widePic ? widePic.split(",")[0] : pic;
      }
      return url;
    }

    /**
     * 推入数据
     */
    pushData(data, item) {
      data.push({
        id: Number(item.id),
        name: item.name,
        img: this.returnGoodsImg(item),
        endTime: item.assembleActivity.activityEndTime,
        beginTime: item.assembleActivity.activityBeginTime,
        actPrice: item.actPrice,
        price: item.price,
        leadPrice: item.leadPrice,
        soldCount: item.soldCount,
        inventory: item.inventory,
        deliveryTime: item.goodTime,
        status: item.flag ? 1 : 2,
        preheatStatus: Number(item.preheatStatus),
        hasTimeTips: item.hasTimeTips,
      });
    }

    /**
     * 进入商品详情
     */
    gotoDetail(e) {
      const goodId = e.currentTarget.dataset.id;
      uni.navigateTo({
        url: `/subcontract/pages/detail/detail?id=${goodId}`,
      });
    }

    /**
     * 格式化时间
     */
    formatTime(time) {
      while (("" + time).indexOf("-") !== -1) {
        time = ("" + time).replace("-", "/");
      }
      return time;
    }
  }
</script>

<style lang="scss" scoped>
  .second__cat-page {
    min-height: 100vh;
    background-color: #f2f2f2;

    .header__box {
      box-sizing: border-box;

      .search__box {
        height: 60px;
        display: flex;
        padding: 0px 10px;
        background-color: #fff;

        .input__iocn {
          flex: 1;
          height: 30px;
          background-color: rgba(228, 228, 228, 1);
          border-radius: 20px;
          margin-top: 3px;
          cursor: pointer;
        }

        .icon__box {
          width: 50px;
          height: 100%;
          position: relative;
          cursor: pointer;
          padding-top: 2px;

          .icon__image {
            float: right;
            width: 50rpx;
            height: 50rpx;
            margin-right: 10rpx;
          }

          .change__item {
            width: 120rpx;
            line-height: 36rpx;
            height: 36rpx;
            text-align: right;
            position: absolute;
            top: 60rpx;
            right: 8rpx;
            font-size: 24rpx;
          }
        }
      }
    }

    .tab__con {
      display: flex;
      background-color: #fff;

      .tab__item {
        flex: 1;
        @include flex();
        text-align: center;
        font-size: 28rpx;
        cursor: pointer;
        height: 80rpx;
      }

      .active__tab {
        color: #FC425A;
      }
    }

    .list__page {
      height: calc(100% - 80px);
    }
  }

  .price__icon {
    width: 50rpx;
    position: relative;
    margin-left: 10rpx;

    .price__icon_up {
      display: inline-block;
      font-size: 22rpx;
      position: absolute;
      top: 18rpx;
      right: 28px;
      color: #ccc;
    }

    .price__icon_down {
      font-size: 22rpx;
      position: absolute;
      top: 40rpx;
      right: 28px;
      color: #ccc;
    }

    .active__icon {
      color: #FC425A;
    }
  }

  .shopNoCar {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 100%;
    height: calc(100vh - 100px);
    background-color: #fff;
    position: relative;
  }

  .shop__noCar {
    margin-top: 70px;
    width: 69%;
  }

  .shop__noCar--text {
    display: block;
    justify-content: center;
    color: #acacac;
    width: 100%;
    text-align: center;
    position: absolute;
    top: 320px;
  }
</style>